﻿// Jinx AJAX Framework
// Copyright (C) 2008 Blake Hegerle
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System.Collections.Generic;
using System.Linq;
using Jinx.Models;
using Jinx.Naming.Paths;
using Jinx.Utility.Locking;

namespace Jinx.Naming
{
    public class NamingContext
    {
        #region Delegates

        public delegate void Invalidated(string Path);

        public delegate void ValueApplied(string Path, object Value);

        #endregion

        private readonly ModelContext context;
        private readonly LockingContext lockingContext;
        private readonly IDictionary<string, ModelBase> ModelMap;

        public NamingContext()
            : this(new LockingContext())
        {
        }

        public NamingContext(LockingContext lockingContext)
        {
            this.lockingContext = lockingContext;
            context = new ModelContext(LockingContext);
            ModelMap = new Dictionary<string, ModelBase>();
        }

        public ModelContext Context
        {
            get { return context; }
        }

        public ModelBase this[string Name]
        {
            get
            {
                using (LockingContext.ReadLock)
                {
                    ModelBase Model;
                    if (ModelMap.TryGetValue(Name, out Model))
                        return Model;
                    
                    throw new ObjectNotFound(Name);
                }
            }
        }

        public ModelContext ModelContext
        {
            get { return context; }
        }

        internal LockingContext LockingContext
        {
            get { return lockingContext; }
        }

        public event Invalidated InvalidatedEvent;
        public event ValueApplied ValueAppliedEvent;

        public T New<T>() where T : class
        {
            return context.New<T>();
        }

        public T NameNew<T>(string ModelName) where T : class
        {
            var Model = ModelFactory<T>.New();
            Name(Model, ModelName);
            return Model.GetProxyInterface();
        }

        public void Name(ModelBase Model, string ModelName)
        {
            context.Register(Model);
            NameInContext(Model, ModelName);
        }

        public void NameInContext(ModelBase Model, string Name)
        {
            NameValidator.Validate(Name);

            Model.MemberChangedEvent += OnMemberDidChange;

            using (LockingContext.WriteLock)
            {
                if (ModelMap.ContainsKey(Name))
                    throw new DuplicateName(Name);

                ModelMap[Name] = Model;
            }
        }

        public IEnumerable<string> Names(ModelBase Model)
        {
            return from MappedPair in ModelMap
                   where MappedPair.Value == Model
                   select MappedPair.Key;
        }

        private void OnMemberDidChange(ModelBase Model, string MemberName, object OldValue, object NewValue)
        {
            foreach (var Path in new PathEnumerator(Model, this).PathStrings)
            {
                if (InvalidatedEvent != null)
                {
                    if (OldValue != null && NewValue == null)
                        InvalidatedEvent(Path);
                }

                if (ValueAppliedEvent == null) continue;
                if (NewValue != null)
                    ValueAppliedEvent(Path, NewValue);
            }
        }
    }
}